﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Globalization;
using System.Linq;
using EstateNuke.Data.Properties;

namespace EstateNuke.Data
{
    public partial class ContractReceipt
    {
        #region Fileds & Properties

        /// <summary>
        /// </summary>
        public bool Received
        {
            get
            {
                return ReceivableAmount == ReceivedAmount;
            }
        }

        /// <summary>
        /// </summary>
        public decimal RemainingAmount
        {
            get
            {
                return ReceivableAmount - ReceivedAmount;
            }
        }

        /// <summary>
        /// </summary>
        public decimal ReceivedAmount
        {
            get
            {
                return InternalContractReceivedReceipts.Where(contractReceivedReceipt => contractReceivedReceipt.IsDeleted == false).Sum(contractReceivedReceipt => contractReceivedReceipt.ReceivedAmount);
            }
        }

        /// <summary>
        /// </summary>
        public ContractReceiptScheduledAlert LatestUnProcessedContractReceiptScheduledAlert
        {
            get
            {
                return InternalContractReceiptScheduledAlerts.FirstOrDefault(smallOrderExpiredAlert => smallOrderExpiredAlert.IsDeleted == false && smallOrderExpiredAlert.Processed == false);
            }
        }

        /// <summary>
        /// </summary>
        public IList<ContractReceiptScheduledAlert> ContractReceiptScheduledAlerts
        {
            get
            {
                return InternalContractReceiptScheduledAlerts.Where(smallOrderExpiredAlert => smallOrderExpiredAlert.IsDeleted == false).ToList();
            }
        }

        /// <summary>
        /// </summary>
        public IList<ContractReceivedReceipt> ContractReceivedReceipts
        {
            get
            {
                return InternalContractReceivedReceipts.Where(contractReceivedReceipt => contractReceivedReceipt.IsDeleted == false).ToList();
            }
        }

        #endregion

        #region Add & Remove ContractReceivedReceipt

        /// <summary>
        /// </summary>
        /// <returns></returns>
        public ContractReceivedReceipt AddContractReceivedReceipt(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            var contractReceivedReceipt = new ContractReceivedReceipt
                                              {
                                                  RowId = Guid.NewGuid(),
                                                  CreatedDate = DateTime.Now,
                                              };
            InternalContractReceivedReceipts.Add(contractReceivedReceipt);
            contractReceivedReceipt.IsDeleted = false;
            contractReceivedReceipt.ModifiedDate = DateTime.Now;
            contractReceivedReceipt.ModifiedByUser = modifiedUser;
            contractReceivedReceipt.ReceivedDate = DateTime.Now;
            contractReceivedReceipt.ReceivedAmount = ReceivableAmount;
            return contractReceivedReceipt;
        }

        /// <summary>
        /// </summary>
        /// <param name = "receivedDate"></param>
        /// <param name = "modifiedUser"></param>
        /// <returns></returns>
        public ContractReceivedReceipt AddContractReceivedReceipt(DateTime receivedDate, User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalContractReceivedReceipts.Any(item => item.IsDeleted == false && item.ReceivedDate == receivedDate))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.DuplicatedContractReceivedReceipt, receivedDate.Date.ToString("yyyy年MM月dd日")));
            }
            var contractReceivedReceipt = InternalContractReceivedReceipts.FirstOrDefault(item => item.IsDeleted && item.ReceivedDate == receivedDate.Date);
            if (contractReceivedReceipt == null)
            {
                contractReceivedReceipt = new ContractReceivedReceipt
                                              {
                                                  RowId = Guid.NewGuid(),
                                                  CreatedDate = DateTime.Now,
                                              };
                InternalContractReceivedReceipts.Add(contractReceivedReceipt);
            }
            contractReceivedReceipt.IsDeleted = false;
            contractReceivedReceipt.ModifiedDate = DateTime.Now;
            contractReceivedReceipt.ModifiedByUser = modifiedUser;
            contractReceivedReceipt.ReceivedDate = receivedDate;
            contractReceivedReceipt.ReceivedAmount = ReceivableAmount;
            return contractReceivedReceipt;
        }

        /// <summary>
        /// </summary>
        /// <param name = "contractReceivedReceipt"></param>
        /// <param name = "modifiedUser"></param>
        public void RemoveContractReceivedReceipt(ContractReceivedReceipt contractReceivedReceipt, User modifiedUser)
        {
            if (contractReceivedReceipt == null)
            {
                throw new ArgumentNullException("contractReceivedReceipt");
            }
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalContractReceivedReceipts.Contains(contractReceivedReceipt))
            {
                contractReceivedReceipt.Delete(modifiedUser);
            }
        }

        #endregion

        #region Create & Remove ContractReceiptScheduledAlert

        /// <summary>
        /// </summary>
        /// <param name = "alertType"></param>
        /// <param name = "modifiedUser"></param>
        public ContractReceiptScheduledAlert CreateContractReceiptScheduledAlert(AlertType alertType, User modifiedUser)
        {
            if (alertType == null)
            {
                throw new ArgumentNullException("alertType");
            }
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (alertType.Id != 40)
            {
                throw new ArgumentException("alertType");
            }
            if (!ContractReference.IsLoaded)
            {
                ContractReference.Load(MergeOption.PreserveChanges);
            }
            if (!Contract.AgreementReference.IsLoaded)
            {
                Contract.AgreementReference.Load(MergeOption.PreserveChanges);
            }
            var reminderDays = alertType.DefaultReminderDays.HasValue ? alertType.DefaultReminderDays : 0;
            var alertTypeReminderDays = Contract.Agreement.Project.AlertTypeReminderDays;
            if (alertTypeReminderDays != null && alertTypeReminderDays.ContainsKey(alertType) && alertTypeReminderDays[alertType] != null && alertTypeReminderDays[alertType].Item1.HasValue)
            {
                reminderDays = alertTypeReminderDays[alertType].Item1;
            }
            if (reminderDays != 0)
            {
                var contractReceiptScheduledAlert = InternalContractReceiptScheduledAlerts.FirstOrDefault(item => item.IsDeleted == false && item.Processed == false);
                if (contractReceiptScheduledAlert == null)
                {
                    contractReceiptScheduledAlert = new ContractReceiptScheduledAlert
                                                         {
                                                             RowId = Guid.NewGuid(),
                                                             CreatedDate = DateTime.Now,
                                                         };
                    InternalContractReceiptScheduledAlerts.Add(contractReceiptScheduledAlert);
                }
                contractReceiptScheduledAlert.IsDeleted = false;
                contractReceiptScheduledAlert.ModifiedDate = DateTime.Now;
                contractReceiptScheduledAlert.ModifiedByUser = modifiedUser;
                contractReceiptScheduledAlert.AlertType = alertType;
                contractReceiptScheduledAlert.RemindDate = ScheduledDate.AddDays((double) reminderDays);
                return contractReceiptScheduledAlert;
            }
            return null;
        }

        /// <summary>
        /// </summary>
        /// <param name = "contractReceiptScheduledAlert"></param>
        /// <param name = "modifiedUser"></param>
        public void RemoveContractReceiptScheduledAlert(ContractReceiptScheduledAlert contractReceiptScheduledAlert, User modifiedUser)
        {
            if (contractReceiptScheduledAlert == null)
            {
                throw new ArgumentNullException("contractReceiptScheduledAlert");
            }
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalContractReceiptScheduledAlerts.Contains(contractReceiptScheduledAlert))
            {
                contractReceiptScheduledAlert.Delete(modifiedUser);
            }
        }

        #endregion

        #region Ensure

        /// <summary>
        /// </summary>
        public void Ensure()
        {
            if (ReceivableAmount < 0)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture, Resources.NonNegativeNumberAllowed, RowId, "ContractReceipt", "ReceivableAmount"));
            }
            ScheduledDate = ScheduledDate.Date;
            Comment = string.IsNullOrEmpty(Comment) ? null : Comment.Length > 512 ? Comment.Substring(0, 512) : Comment;
        }

        #endregion

        #region Delete

        /// <summary>
        /// </summary>
        public void Delete(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            IsDeleted = true;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
            ((List<ContractReceivedReceipt>) ContractReceivedReceipts).ForEach(contractReceivedReceipt => contractReceivedReceipt.Delete(modifiedUser));
            ((List<ContractReceiptScheduledAlert>) ContractReceiptScheduledAlerts).ForEach(contractReceiptScheduledAlert => contractReceiptScheduledAlert.Delete(modifiedUser));
        }

        /// <summary>
        /// </summary>
        public void CancelDelete(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            IsDeleted = false;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
        }

        #endregion
    }
}